package com.shou.controller.phone;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.shou.CommonVar;
import com.shou.controller.MyController;
import com.shou.dao.support.Page;
import com.shou.entity.Collection;
import com.shou.entity.District;
import com.shou.entity.PictureTextMsg;
import com.shou.entity.ServeInfo;
import com.shou.entity.ServeType;
import com.shou.entity.SlideShow;
import com.shou.entity.User;
import com.shou.entity.weixinbean.AccessToken;
import com.shou.entity.weixinbean.WeixinUser;
import com.shou.service.impl.ActivityService;
import com.shou.service.impl.ServeInfoService;
import com.shou.service.impl.SlideShowService;
import com.shou.service.impl.UserService;
import com.shou.util.ValidatorUtils;
import com.shou.util.WeixinUtil;

@Controller("phoneServeController")
@RequestMapping("/phone/serveInfo")
public class ServeController extends MyController{

	@Autowired
	ServeInfoService serveInfoService;
	
	@Autowired
	SlideShowService slideShowService;
	
	@Autowired
	UserService userService;
	
	@Autowired
	ActivityService activityService;
	
	@RequestMapping("/index")
	public String serveList(HttpServletRequest request,Model model) {
		
		/********测试数据，模拟用户登录的入口**********/
		User user = new User();
		user.setId(1L);
		user.setNickname("刘欣星");
		user.setHeadimgurl("http://wx.qlogo.cn/mmopen/PL5y7QQHZgJicBb9y5ibeyHIydlrccylPOqYK08icarePso7zyyedGumdHTvv5MjZsLVjibdunBqNhiaMYRO0J5KNmBBicJv9Ol3Fh/0");	
		user.setSex(1);
	    request.getSession().setAttribute(CommonVar.SESSION_WEIXIN, user);
	    
	    
	    
		List<SlideShow> list = slideShowService.slideShowUsefulList();
	    model.addAttribute("slideShow",list);
	    
	    PictureTextMsg text = activityService.getPictureText("index");
	    model.addAttribute("text", text);
	    
		return "/phone/serveInfo/index";
	}
	
	/**
	 * 微信登录
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 */
	@RequestMapping(value="/weixinLogin")
	public String weixinLogin(Model model,HttpServletRequest request,HttpServletResponse response,String code) {
		Boolean success = true;
		String msg = "请求成功";
		try{			
		    if(StringUtils.isNotBlank(code)) {  
		    	userService.login(request, code);		    	
		    }
		    else{
		    	//if (StringUtils.isBlank(openId)) {
				String redirect_uri = getWebSite(request) + "/phone/serveInfo/weixinLogin.htm";
				String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +userService.getConfig("WEIXIN_APPID") + "&redirect_uri=" + redirect_uri + "&response_type=code&scope=snsapi_base&state=state1#wechat_redirect";
				response.sendRedirect(url);		
				return null;
			}
		}
		catch(Exception e){
			e.printStackTrace();
			success = false;
			msg = "请求失败";
			log.error("登录平台失败",e);
		}		
		model.addAttribute("status",success);
		model.addAttribute("msg",msg);
		
		return "redirect:/phone/serveInfo/index.htm";
	}
	
	/**
	 * 分页获取首页服务信息
	 * @param pageSize
	 * @param pageNum
	 * @return
	 */
	@RequestMapping("/getServePage")
	public ResponseEntity<String> getServePage(HttpServletRequest request,Integer pageSize,Integer pageNum) {
		String msg = "请求成功";
		Boolean status = true;
		Page<ServeInfo> page = null;
		try{
			User user = (User)request.getSession().getAttribute(CommonVar.SESSION_WEIXIN);
			page = serveInfoService.getServePage(pageNum, pageSize,user.getId(), null);
		}
		catch(Exception e){
			status = false;
			msg = "请求失败";
			log.error("分页获取第"+pageNum+"服务列表失败:",e);
			e.printStackTrace();
		}
		return renderPageData(status, msg, page);
		//return renderJsonpData(request, renderPageData(status, msg, page));
	}
	
	/**
	 * 跳转发布服务，选择服务类型页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/publish")
	public String pushServeTypePage(Model model) {	
		
		List<District> list = serveInfoService.getDistrictList();
		model.addAttribute("districtList", list);
		
		return "/phone/serveInfo/publish";
	}
	
	/**
	 * 获取区域列表
	 * @return
	 */
	@RequestMapping("/getDistrictList")
	public ResponseEntity<String> getDistrictList(){
		String msg = "请求成功";
		Boolean status = true;
		List<District> list = null;
		try{
			list = serveInfoService.getDistrictList();
		}
		catch(Exception e) {
			status = false;
			msg = "请求失败";
			log.error("获取serveType失败",e);
			e.printStackTrace();
		}
		return renderData(status, msg, list);
	}
	
	/**
	 * 获取服务种类
	 * @return
	 */
	@RequestMapping("/getServeTypeList")
	public ResponseEntity<String> getServeTypeList() {
		String msg = "请求成功";
		Boolean status = true;
		List<ServeType> list = null;
		try{
			list = serveInfoService.getServeTypeList();
		}
		catch(Exception e) {
			status = false;
			msg = "请求失败";
			log.error("获取serveType失败",e);
			e.printStackTrace();
		}
		return renderData(status, msg, list);
	}
	

/*	@RequestMapping("/pushServeInfo")
	public String pushServeInfoPage(Model model,Integer serveTypeId) {
		model.addAttribute("serveTypeId", serveTypeId);
		return "/phone/serveInfo/pushServeInfo";
	}*/
	
	/**
	 * 保存服务信息
	 * @param serveInfo
	 * @return
	 */
	@RequestMapping("/saveServe")
	public ResponseEntity<String> saveServe(HttpServletRequest request, ServeInfo serveInfo) {
		
		String msg = "保存成功";
		Boolean status = true;
		
		User user =	(User)request.getSession().getAttribute(CommonVar.SESSION_WEIXIN);
		if(user == null) {
			msg = "please log in correctly!";
			status = false;
		}
		else {
			serveInfo.setUserId(user.getId());
		}
		if(serveInfo.getServeTypeId() == null){
			msg = "请选择服务类型";
			status = false;
		}
		else if(serveInfo.getDistrictId() == null) {
			msg = "请选择区域";
			status = false;
		}
		else if(StringUtils.isBlank(serveInfo.getTitle())) {
			msg = "请填写标题";
			status = false;
		}
		else if(StringUtils.isBlank(serveInfo.getDiscription())){
			msg = "请填写描述";
			status = false;
		}
		else if(!ValidatorUtils.isPhoneNumber(serveInfo.getContactPhone())){
			msg = "手机号码格式不正确";
			status = false;
		}
		else if(StringUtils.isBlank(serveInfo.getContactName())){
			msg = "请填写联系人姓名";
			status = false;
		}
		else {			
			try{
				serveInfoService.saveServeInfo(serveInfo);
			}
			catch(Exception e){
				status = false;
				msg = "保存失败";
				String userId = serveInfo.getUserId() == null ? "null":serveInfo.getUserId().toString();
				log.error(userId+"添加serveInfo失败",e);
				e.printStackTrace();
			}
		}
		return renderMsg(status, msg);
	}
	
	
}
